import logging

from fastapi import Request
from starlette.responses import JSONResponse
from starlette.status import HTTP_401_UNAUTHORIZED

from odoo.addons.fastapi.context import odoo_env_ctx
from odoo.addons.web_api.exceptions.http_exception import AuthException

_logger = logging.getLogger(__name__)


# 回滚
def _rollback(request: Request, reason: str) -> None:
    cr = odoo_env_ctx.get().cr
    if cr is not None:
        _logger.debug("rollback on %s", reason)
        cr.rollback()


async def auth_exception_handler(
        request: Request, exc: AuthException
) -> JSONResponse:
    return JSONResponse(
        status_code=HTTP_401_UNAUTHORIZED,
        content={"msg": '未登录', 'code': HTTP_401_UNAUTHORIZED, 'data': []}
    )


async def odoo_auth_exception_handler(request: Request, exc: AuthException) -> JSONResponse:
    _rollback(request, reason=str(exc))
    return await auth_exception_handler(request, exc)
